<template>
	<view>
		<view class="bluetooth-page">
			<view class="main" @click="drawerShow = false;">
				<view ref="img" class="img123">
					<movable-area class="movable-area">
						<view class="img" @click="createDot">
							<movable-view class="wrap dot-item" v-for="(item,index) in dotData" :key="item.index"
								:x="item.x" :y="item.y" direction="all"
								@change="(e)=> onChange(e,item.value,index,'dot')"
								@touchstart.stop="touchinUk($event,item,index,'dot')"
								@touchend.stop="cleartime(item,index,'dot')" @click.stop="viewFile(item)">
								<text v-if="item.value">{{item.value}}</text>
								<image v-if="item.value" style="width: 60rpx;height: 60rpx;" :src="fileTypeIcon(item)"
									mode=""></image>
							</movable-view>
							<image :src="imgSrc" mode=""></image>
						</view>
						<movable-view class="item rebound" v-for="(item,index) in reboundCoordinate" :key="index"
							:x="item.x" :y="item.y" direction="all"
							@change="(e)=> onChange(e,item.value,index,'rebound')"
							@touchstart.stop="touchinUk($event,item,index,'rebound')"
							@touchend.stop="cleartime(item,index,'rebound')">
							{{item.value}}(<text class="num">{{index+1}}</text>)
						</movable-view>
						<view class="form">
							<view class="wrap">
								<view class="item">图纸名称：<text>{{formData.name}}</text> </view>
								<view class="item">制图单位：<text>{{formData.planOrg}}</text></view>
								<view class="item">制图人：<text>{{formData.planPerson}}</text></view>
								<view class="item">审图人：<text>{{formData.applyPlanPerson || '--'}}</text></view>
								<view class="item">起火地址：<text>{{formData.address}}</text></view>
								<view class="item">
									起火时间：<text>{{$u.timeFormat(formData.fireTime, 'yyyy/mm/dd hh:MM:ss')}}</text></view>
								<view class="item">
									制图时间：<text>{{$u.timeFormat(formData.doPlanTime, 'yyyy/mm/dd hh:MM:ss')}}</text>
								</view>
							</view>
						</view>
						<view class="compass">
							<image :src="icon_compass" mode=""></image>
						</view>
						<view class="ruler">
							<image :src="icon_ruler" mode=""></image>
						</view>
					</movable-area>
				</view>
				<button type="primary" @click="canvasImage.createImg" :prop="msg"
					:change:prop="canvasImage.create">保存信息</button>
			</view>
			<u-popup v-model="dotShow" mode="left" @close="dotClosePopup">
				<view class="dot">
					<view v-for="(notice,index) in noticeList" :key="notice.noticeId">
						<view class="title">
							{{notice.moduleName}}
						</view>
						<view class="notice-wrap" v-if="notice.fileList.length > 0">
							<view v-for="(file,index2) in notice.fileList" :key="index2">
								<view class="wrap" @click="addDot(file)">
									<view class="icon">
										<image :src="fileTypeIcon(file)" mode=""></image>
									</view>
									<view class="file">
										{{file.name}}
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty">
							<u-empty style="width: 280rpx;" text="暂无数据" mode="data"></u-empty>
						</view>
					</view>
				</view>
			</u-popup>
			<view class="right-dialog" :class="{drwaer:!drawerShow}">
				<view class="body">
					<view class="pairedDevices">
						<view class="title">
							<text>已配对的设备</text>
						</view>
						<view>
							<view class="item" v-for="device in pairedDevices">
								<text>{{device.name}}</text>
								<button class="btn" size="mini" type="primary"
									@click="connDevice(device.address,device)">
									连接
								</button>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="drawer-btn" @click.stop="onDrwaerShow" v-if="!drawerShow">
				<view class="content">
					配对设备
				</view>
			</view>
			<u-modal v-model="removeObj.show" :content="removeObj.content" show-cancel-button @confirm="removeConfirm">
			</u-modal>

			<u-popup v-model="viewFileObj.show" mode="center" @close="viewFileClose">
				<image style="width: 1500rpx;height: 1000rpx;" v-if="viewFileObj.type == 'image'" :src="viewFileObj.url"
					mode="aspectFit"></image>
				<video v-if="viewFileObj.type == 'video'" :src="viewFileObj.url"></video>
			</u-popup>

		</view>
	</view>
</template>
<script>
	import BluetoothTool from '../../static/common/js/bluetoothTool.js'
	import {
		dataURLtoFile,
		pathToBase64,
		base64ToPath
	} from '../../static/common/js/util.js'
	import {
		icon_location,
		icon_compass,
		icon_ruler,
		icon_video,
		icon_image,
		icon_pdf
	} from './base64/index.js'
	import {
		MODULE_DICTID,
		MODULE_DICTID_NAMES
	} from '@/const/modules'
	import {
		getLocalNotice,
		getLocalArchivesDetail,
		getLocalNoticeList,
		uploadLocalFile,
		createLocalNotice
	} from '@/static/common/js/padLocalFileHandler.js'
	export default {
		data() {
			return {
				icon_location,
				icon_compass,
				icon_ruler,
				icon_video,
				icon_image,
				icon_pdf,
				bluetoothState: {},
				pairedDevices: [],
				newDevices: [],
				receiveDataArr: [],
				sendData: '',
				msg: 'msg',
				bluetoothTool: '',
				drawerShow: false,
				imgSrc: 'http://192.168.0.236:8065/profile/upload/2022/04/26/webp.png',
				x: 0,
				y: 0,
				jsonStr: [],
				formData: {},
				reboundCoordinate: [],
				removeObj: {
					show: false,
					content: '确定删除该项吗？',
					type: ''
				},
				removeItem: {},
				Loop: 0,
				isChange: true,
				currentIndex: null,
				currentXY: {},
				connDeviceObj: {},
				createDotObj: {
					index: null
				},
				dotData: [],
				dotShow: false,
				dotList: [{
					label: 'image',
					value: 0
				}, {
					label: 'video',
					value: 1
				}, {
					label: 'pdf',
					value: 2
				}],
				radioValue: 0,
				viewFileObj: {
					show: false,
					type: null
				},
				noticeList: [],
				dictIdNames: [],
				noteItemForm: {}
			}
		},
		computed: {
			receiveDataStr: function() {
				return String.fromCharCode.apply(String, this.receiveDataArr)
				// return String.fromCharCode(this.receiveDataArr)
			},
			bluetoothStatusDesc: function() {
				return this.bluetoothStatus ? '已开启' : '已关闭'
			},
			dotLabel() {
				return (val) => {
					if (val != 0 && !val) {
						return ''
					}
					return this.dotList[parseFloat(val)].label
				}
			},
			getMainFileType() {
				return (file) => {
					if (file.type == 'application/pdf') return 'pdf'
					if (file.type && file.type.indexOf('/') != '-1') return file.type.split('/')[0]
					if (file.url && file.url.indexOf('.') != '-1') {
						const extension = file.url.split('.').pop().toLowerCase();
						const fileTypeMapping = {
							jpg: 'image',
							jpeg: 'image',
							png: 'image',
							gif: 'image',
							mp4: 'video',
							mov: 'video',
							avi: 'video',
							wmv: 'video',
						};
						const fileType = fileTypeMapping[extension] || '未知类型';

						return fileType;
					}
					if (!file.type) return '未知类型'
				}
			},
			fileTypeIcon() {
				return (file) => {
					const fileTypeIconMap = {
						'image': icon_image,
						'video': icon_video,
						'pdf': icon_pdf,
					}
					return fileTypeIconMap[this.getMainFileType(file)]
				}
			},
			getModuleName() {
				return (keyName) => {
					const str = keyName.toLowerCase();
					const foundKey = Object.keys(MODULE_DICTID).find((key) => str.includes(key));
					if (foundKey) {
						const moduleId = MODULE_DICTID[foundKey];
						return MODULE_DICTID_NAMES[moduleId];
					}
					return null; // 或其他适当的默认值
				}
			},
			dictId() {
				return MODULE_DICTID.sketch
			},
		},
		onLoad(params) {
			this.params = params
			this.getDetailByNoticeId(params)
			this.getDetailByNoticeIds(params)
		},
		created() {
			let that = this
			// 		this.bluetoothTool = BluetoothTool()
			// 		this.bluetoothState = this.bluetoothTool.state
			// 		this.bluetoothTool.init({
			// 			listenBTStatusCallback: function(state) {
			// 				that.msg = '蓝牙状态: ' + state
			// 			},
			// 			discoveryDeviceCallback: function(newDevice) {
			// 				that.newDevices.push(newDevice)
			// 			},
			// 			discoveryFinishedCallback: function() {
			// 				that.msg = '搜索完成'
			// 			},
			// 			readDataCallback: function(dataByteArr) {
			// 				let dataByteArrMap = dataByteArr.map(item => {
			// 					that.$u.api.deviceData.add({
			// 						deviceId: that.connDeviceObj.deviceId,
			// 						data: item
			// 					}).then(res => {})
			// 					return {
			// 						value: item,
			// 						x: 0,
			// 						y: 0
			// 					}
			// 				})
			// 				that.receiveDataArr.push.apply(
			// 					that.receiveDataArr,
			// 					dataByteArr
			// 				)
			// 				that.reboundCoordinate.push.apply(
			// 					that.reboundCoordinate,
			// 					dataByteArrMap
			// 				)
			// 			},
			// 			connExceptionCallback: function(e) {
			// 				that.msg = '设备连接失败'
			// 			},
			// 		})

		},
		mounted() {
			// this.getPairedDevices()
		},
		methods: {
			dotClosePopup() {
				// let lastIndex = this.dotData.length - 1; // 获取最后一项的索引  
				// this.dotData.splice(lastIndex, 1); // 删除最后一项  
				// this.dotShow = false
			},
			createDot(e) {
				if (this.drawerShow) {
					return this.drawerShow = false
				}
				const {
					x,
					y
				} = e.target
				let index = this.dotData.length
				this.dotData.push({
					index: index,
					x,
					y,
					value: null
				})
				this.createDotObj.index = this.dotData.length - 1
				this.dotShow = true
			},
			addDot(row) {
				let item = this.dotData[this.createDotObj.index]
				let newItem = Object.assign(item, {
					...row,
					value: row.name
				})
				this.dotData[this.createDotObj.index] = newItem
				this.dotShow = false
			},
			viewFile(file) {
				if (this.getMainFileType(file) == 'pdf') {
					let url = file.url
					uni.navigateTo({
						url: `/pages/common/pdfWebview?title=${file.name}&fileUrl=${encodeURIComponent(url)}`
					})
					return
				}
				this.viewFileObj.type = this.getMainFileType(file)
				this.viewFileObj.url = file.url
				this.viewFileObj.show = true
			},
			viewFileClose() {
				this.viewFileObj.type = null
				this.viewFileObj.url = null
				this.viewFileObj.show = false
			},
			radioGroupChange(e) {
				// this.dotData[this.createDotObj.index].type = e
			},
			async getDetailByNoticeId(params) {
				// 目前只有现场草图可以跳转到这里，暂时写死
				let res = await getLocalNotice(params.archivesId, MODULE_DICTID.sketch, params.keyId)
				const currentImg = res.fileList[params.imgIndex]
				this.noteItemForm = res
				pathToBase64(currentImg.url).then((base64) => {
					this.imgSrc = base64
					this.formData = currentImg
					this.reboundCoordinate = currentImg.reboundCoordinate || this.reboundCoordinate
					this.dotData = currentImg.dotData || this.dotData
				})


				return
				// let res = await this.$u.api.sketch.getFileTabInfo({
				// 	fileId: params.fileId
				// })
				// const currentImg = res.data
				// this.src = currentImg.url
				// this.formData = currentImg
				// this.reboundCoordinate = currentImg.reboundCoordinate || this.reboundCoordinate
				// this.dotData = currentImg.dotData || this.dotData
			},
			async getDetailByNoticeIds(params) {

				const {
					evidence,
					photo,
					video
				} = MODULE_DICTID
				this.dictIdNames = [MODULE_DICTID_NAMES[evidence], MODULE_DICTID_NAMES[photo], MODULE_DICTID_NAMES[
					video]]
				let res = await getLocalArchivesDetail(params.archivesId)
				let res1 = await getLocalNoticeList(params.archivesId, res.archivesType)
				const res1MapList = res1.filter(item => {
					return [evidence, photo, video].includes(parseInt(item.dictId))
				}).map(item => {

					let fileList = []
					item.mapList.forEach(itemMap => {
						fileList.push(...itemMap.fileList)
					})
					let moduleName = MODULE_DICTID_NAMES[parseInt(item.dictId)]
					return {
						noticeId: item.noticeId,
						moduleName,
						fileList
					}
				})
				this.noticeList = res1MapList
				// let data = await getLocalNotice(archivesId, dictId, keyId)
				return
				// let res = await this.$u.api.sketch.getTabFileList({
				// 	archivesId: params.archivesId
				// })

				// this.noticeList = res.data
			},
			getDeviceList() {
				this.$u.api.device.list().then(res => {
					if (res.code == 200) {
						let devices = []
						res.rows.forEach(device => {
							this.pairedDevices.forEach(item => {
								if (item.name == device.macAddress) {
									devices.push({
										...device,
										address: item.address
									})
								}
							})
						})
						this.pairedDevices = devices
					}
				})
			},
			onDrwaerShow() {
				this.drawerShow = true
			},
			onViewClick(options) {
				// uni.showLoading({
				// 	title: '加载中',
				// 	mask: true
				// });
				let jsonStr = this.jsonStr
				const currentImg = this.formData
				currentImg['reboundCoordinate'] = this.reboundCoordinate
				currentImg['dotData'] = this.dotData
				let fileName = new Date().getTime() + '.jpg'
				try {
					base64ToPath(options.base64).then(async fileUrl => {
						let fileName = fileUrl.match(/\/([^/]+)$/)[1];
						let fileLocalUrl = await uploadLocalFile(this.params.archivesId, {
							url: fileUrl,
							name: fileName,
							type: 'image',
						})
						currentImg['newUrl'] = fileLocalUrl
						console.log(currentImg);
						this.noteItemForm.fileList[this.params.imgIndex] = currentImg
						console.log(this.noteItemForm);
						let res = await createLocalNotice(this.params.archivesId, this.dictId, this.params
							.keyId,
							false, this.noteItemForm)
						uni.hideLoading();
					})


				} catch (error) {
					uni.hideLoading();
				}
			},
			onChange(e, item, index) {
				this.isChange = true
				let {
					x,
					y
				} = e.detail
				this.currentXY = {
					x,
					y
				}
				this.currentIndex = index
			},
			touchinUk(event, item, index, key) {
				var that = this;
				clearTimeout(this.Loop); //再次清空定时器，防止重复注册定时器
				this.Loop = setTimeout(() => {
					that.Loop = 0;
					event.preventDefault();
					that.removeIndex = index
					if (!that.isChange) {
						that.removeObj.show = true;
						that.removeIndex = index
						that.removeObj.type = key
					}
				}, 800);
				return false
			},
			cleartime(item, index, keyName) {
				const {
					x,
					y
				} = this.currentXY
				if (keyName == 'dot') {
					this.dotData[this.currentIndex].x = x
					this.dotData[this.currentIndex].y = y
				} else {
					this.reboundCoordinate[this.currentIndex] = {
						value: item.value,
						x,
						y
					}
				}

				this.isChange = false
				var that = this;
				clearTimeout(this.Loop);
				if (that.Loop != 0) {
					//单击事件（click）
				}
				return false;
			},
			removeConfirm() {
				const index = this.removeIndex
				if (this.removeObj.type == 'dot') {
					this.dotData.splice(index, 1)
				} else {
					this.reboundCoordinate.splice(index, 1)
				}
			},
			turnOnBluetooth: function() {
				this.bluetoothTool.turnOnBluetooth()
			},
			turnOffBluetooth: function() {
				this.bluetoothTool.turnOffBluetooth()
			},
			getPairedDevices: function() {
				this.pairedDevices = this.bluetoothTool.getPairedDevices()
				this.getDeviceList()
			},
			discoveryNewDevice: function() {
				this.newDevices = []
				this.bluetoothTool.discoveryNewDevice()
			},
			cancelDiscovery: function() {
				this.bluetoothTool.cancelDiscovery()
			},
			connDevice: function(address, item) {
				this.bluetoothTool.connDevice(address)
				this.connDeviceObj = item
			},
			disConnDevice: function() {
				this.bluetoothTool.disConnDevice()
			},
			onSendData: function() {
				this.bluetoothTool.sendData(this.sendData)
			},
		},
	}
</script>
<script module="canvasImage" lang="renderjs">
	import html2canvas from 'html2canvas';
	export default {
		mounted() {

		},
		methods: {
			create(msg) {},
			createImg(event, ownerInstance) {
				const timeout = setTimeout(() => {
					const dom = document.querySelector('.img123');
					html2canvas(dom, {
						width: dom.offsetWidth, //设置canvas尺寸与所截图尺寸相同，防止白边
						height: dom.offsetHeight, //防止白边
						logging: true,
						useCORS: true,
					}).then(canvas => {
						const base64 = canvas.toDataURL('image/jpeg', 1);
						ownerInstance.callMethod('onViewClick', {
							base64: base64
						})
					})
					// clearTimeout(timeout);
				}, 500);
				// var canvas = document.querySelector('.img123'), //获取canvas
				// 	ctx = canvas.getContext("2d"), //对应的CanvasRenderingContext2D对象(画笔)
				// 	img = new Image(), //创建新的图片对象
				// 	base64 = ''; //base64 
				// img.src = 'http://www.xxxx.png';
				// img.setAttribute("crossOrigin", 'Anonymous')
				// img.onload = function() { //图片加载完，再draw 和 toDataURL
				// 	ctx.drawImage(img, 0, 0);
				// 	base64 = canvas.toDataURL("image/png");
				// };
			}
		}
	}
</script>
<style lang="scss">
	// .test {
	// 	.title {
	// 		display: flex;
	// 		padding: 20upx;

	// 		text {
	// 			font-size: 60upx;
	// 		}
	// 	}

	// 	.tit {
	// 		font-size: 40upx;
	// 		margin-bottom: 20upx;
	// 	}

	// 	.item {
	// 		padding: 20upx;
	// 		border: 1px solid #ddd;
	// 		background-color: $u-border-color;
	// 		margin-bottom: 20upx;
	// 	}
	// }

	.bluetooth-page {
		.main {
			height: 100vh;
		}

		.img {
			margin: 80upx;
			border: 1px solid $u-border-color;
			height: 800upx;

			.wrap {
				display: flex;
				align-items: center;
				background-color: #d9e7fb73;

				text {
					max-width: 300rpx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}
		}

		.right-dialog {
			z-index: 1001;
			position: fixed;
			right: 0;
			top: 0;
			background-color: $u-card-bg-color;
			box-shadow: 0px 3px 8px 0px #ddd;
			transition: 0.5s;

			&.drwaer {
				right: -520upx;

			}

			.body {
				width: 500upx;
				height: 100vh;

				.pairedDevices {
					height: 100%;
				}

				.title {
					width: 100%;
					display: flex;
					align-items: center;
					height: 40upx;
					margin-bottom: 20upx;

					&:before {
						content: '';
						width: 6upx;
						height: 100%;
						background-color: red;
						margin-right: 10upx;
					}

					text {
						font-size: 32upx;
					}
				}

				.item {
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 20upx;
					border: 1px solid $u-border-color;
					background-color: $u-border-color;
					margin-bottom: 20upx;

					.btn {
						margin: 0;
					}
				}
			}
		}

		.drawer-btn {
			position: fixed;
			top: 50%;
			transform: translateY(-50%);
			right: 0;
			background-color: #fff;
			width: 72upx;
			height: 200upx;
			border: 1px solid $u-border-color;

			.content {
				padding: 10px;

			}
		}

		.dot {
			.title {
				font-weight: bold;
				font-size: 30rpx;
				margin-bottom: 10rpx;
			}

			image {
				width: 100rpx;
				height: 100rpx;
			}
		}
	}

	.rebound {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100upx;
		width: 100upx;
		border-radius: 50%;
		background-color: #2B6FF0;
		color: #fff;
		z-index: 1000;
	}

	.dot-item {
		width: 300upx;
		height: 100upx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #d9e7fb73;
		z-index: 99;

		text {
			max-width: 300rpx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}

	movable-area {
		height: 100%;
		width: 100%;
		overflow: hidden;
		position: relative;

		.form {
			z-index: 999;
			border: 1px solid $u-border-color;
			padding: 10upx;
			position: absolute;
			right: 90upx;
			bottom: 90upx;
			width: 300upx;
			background-color: #fff;
			color: #333;

			text {
				color: $u-light-color;
			}
		}

		.compass {
			border: 1px solid $u-border-color;
			padding: 10upx;
			position: absolute;
			top: 0;
			right: 0;
			width: 150rpx;
			height: 150rpx;
			background-color: #fff;
			color: #333;
		}

		.ruler {
			position: absolute;
			top: 0;
			left: 0;
			width: 150rpx;
			height: 150rpx;
			background-color: #fff;
			color: #333;
			border: 1px solid #000;
		}
	}
</style>